"use client";
import { FC, PropsWithChildren, useEffect, useMemo, useState } from "react";
import HeaderBack from "@/components/HeaderBack";
import ButtonOwn from "@/components/ButtonOwn";
import DomainFooter from "@/components/DomainFooter";
import './page.scss'
import React from "react";
import {getFindPwdApi} from "@/api/user";
import { useSearchParams } from "next/navigation";
import { useRouter } from "@/i18n";

interface Props {}

const ResetPhone: FC<PropsWithChildren<Props>> = () => {
    const router:any = useRouter()

    let searchParams = useSearchParams();
    let user_phone = searchParams.get('userPhone')
    let code = searchParams.get('code')

    let [fromParam, setFromParam] = useState({
        pwd: '',
        againPwd: ''
    })

    const setInputVal = (e: { target: { name: any; value: any; }; }) => {
        const {name, value} = e.target;
        setFromParam({
            ...fromParam,
            [name]: value
        })
    }

    const verifyPwd = (e: any) => {
        let pwd = e.target.value || '';
        pwd.replaceAll(/[^a-zA-Z0-9_-]/g, '')
        setFromParam({ ...fromParam, pwd })
    }

    const activeCls = useMemo(() => {
        let { pwd, againPwd } = fromParam
        if (pwd && againPwd && pwd.length==againPwd.length) {
            return true
        }
        return false
    }, [fromParam]);

    let [msgError, setMsgError] = useState('')
    const findPwdRequest = () => {
        let { pwd, againPwd } = fromParam
        if (pwd && againPwd && pwd!=againPwd) {
            setMsgError('两次输入的密码不相同')
            return true
        }
        getFindPwdApi({user_phone, code, pwd}).then((res) => {
            setMsgError(res.msg || '')
            if(res.code == 200) {
                alert('修改成功')
                router.replace('/login')
            }
        })
    }

    return (
        <div className="confirmPassword-box">
            <HeaderBack />
            <div className="main">
                <div className="title">
                    <h2>Ativa a sua conta por entrar a Senha de Verificação!</h2>
                    <div>A senha de verificação foi enviado para o teu telemóvel 16982013895</div>
                </div>
                <div className="phoneInput">
                    <input name="pwd" type="password" value={fromParam.pwd} onChange={setInputVal} onInput={verifyPwd} placeholder="Senha" maxLength={12}/>
                </div>
                <div className="phoneInput">
                    <input name="againPwd" type="password" value={fromParam.againPwd} onChange={setInputVal} placeholder="Senha" maxLength={12}/>
                </div>
                { msgError && <div className="tips"> {msgError} </div> }
                <div className="btnContent">
                    <ButtonOwn active={activeCls} callbackFun={findPwdRequest}>Completar</ButtonOwn>
                </div>
            </div>
            <DomainFooter />
        </div>
    );
};

export default ResetPhone;
